import { Component, OnInit, ComponentFactoryResolver, ViewChild, ViewContainerRef } from '@angular/core';
import { FirstChildComponent } from '../first-child/first-child.component';

@Component({
  selector: 'app-first',
  templateUrl: './first.component.html',
  styleUrls: ['./first.component.css']
})
export class FirstComponent implements OnInit {

  data: any;

  @ViewChild('dynamicContainer', { read: ViewContainerRef})
  dynamicContainer: ViewContainerRef;

  constructor(
    private componentFactoryResolver: ComponentFactoryResolver
  ) { }

  ngOnInit() {
    setTimeout(() => {
      this.createComponent();
    }, 3000);
  }

  createComponent() {
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(FirstChildComponent);
    this.dynamicContainer.clear();
    this.dynamicContainer.element.nativeElement.innerHTML = '';
    const compoenntRef = this.dynamicContainer.createComponent(componentFactory);
    compoenntRef.instance.title = '我是动态创建的子组件';
    console.log(compoenntRef);
  }

}
